//初始化SDK实例
import cloudbase from '@cloudbase/js-sdk'
const app = cloudbase.init({
    env: 'lowcode-2gxh0baw4d19d595',
})
export const db = app.database()
export const _ = db.command
const auth = app.auth({
    persistence: 'local',
})

// 登陆
export async function login() {
    // 调用匿名登录接口
    await auth.anonymousAuthProvider().signIn()
    // 匿名登录成功后，登录状态isAnonymous字段值为true
    const loginState = await auth.getLoginState()
    console.log(loginState.isAnonymousAuth) // true
}
// 获取临时路径
const getTempFileURL = (fileList) => {
    app.getTempFileURL({
        fileList,
    }).then((res) => {
        console.log(res.fileList)
    })
}
// 上传文件
export const uploadFile = async (dir, file) => {
    const result = await app.uploadFile({
        // 云存储的路径
        cloudPath: dir,
        // 需要上传的文件，File 类型
        filePath: file,
    })
    return result
}

// 插入数据
export const insert = (params) => {
    const { table, data } = params
    return db.collection(table).add({
        ...data,
        createTime: Date.now(),
    })
}

// 更新数据
export const update = async (params) => {
    const { table, _id, data = {} } = params
    console.log('update', params)
    const res = await db.collection(table).doc(_id).update(data)
    console.log(res)
    return res.data
}

// 查询数据
export const query = async (params) => {
    const { table, data = {} } = params
    const res = await db.collection(table).where(data).orderBy('createTime', 'desc').get()
    return res.data
}
// 删除多数据
export const del_mult = async (params) => {
    const { table, data = {} } = params
    const res = await db.collection(table).where(data).remove()
}
// 删除单数据
export const del = async (params) => {
    const { table, _id } = params
    const res = await db.collection(table).doc(_id).remove()
}

// 云函数
export const callFunction = (fn, data) => {
    return app.callFunction({
        // 云函数名称
        name: fn,
        // 传给云函数的参数
        data,
    })
}
